<?php declare(strict_types=1);


namespace App\Model\Logic;

use Swoft\Db\DB;
use App\Model\Entity\Tags;

class Qa
{
    public static function withTag(int $id, int $page)
    {
        $result = [
            'count' => self::countSelect('find_in_set(' . $id . ',tags)'),
            'data'  => self::pageSelect('*', 'find_in_set(' . $id . ',tags)', $page)
        ];
        return $result;
    }

    private static function countSelect(string $where)
    {
        $prefix   = config('prefix');
        $pageSize = config('pagesize', 20);
        $select   = 'count(*) as c';
        $sql      = 'select sum(a.c) as sum from (';
        for ($i = 1; $i <= config('max_table_no'); $i++) {
            $sql .= ("select $select from $prefix" . "question" . str_pad((string)$i, 3, '0', STR_PAD_LEFT) . " where $where union all ");
        }
        $sql    = rtrim($sql, 'union all ') . ') as a';
        $result = DB::selectOne($sql);
        return ceil($result['sum'] / $pageSize);
    }

    private static function pageSelect(string $select, string $where, int $page, string $order = 'sortorder', string $sort = 'DESC')
    {
        $pageSize = config('pagesize', 20);
        $page     = ($page - 1) * $pageSize;
        $prefix   = config('prefix');
        $sql      = '';
        for ($i = 1; $i <= config('max_table_no'); $i++) {
            $sql .= ("select $select from $prefix" . "question" . str_pad((string)$i, 3, '0', STR_PAD_LEFT) . " where $where union all ");
        }
        $sql      = 'select ' . $select . ' from (' . rtrim($sql, 'union all ') . ') as a order by `a`.`' . $order . '` ' . $sort . ',`sof_id` DESC limit ' . $page . ',' . $pageSize;
        $result   = DB::select($sql);
        $tag_list = [];
        if ($result) {
            $tag_ids  = array_column($result, 'tags');
            $tag_list = Tags::whereRaw('id in (' . implode(',', $tag_ids) . ')')->pluck('name', 'id')->toArray();
        }
        foreach ($result as $index => $item) {
            $result[$index]['tags'] = explode(',', $result[$index]['tags']);
        }

        return ['list' => $result, 'tag_list' => $tag_list];
    }

    public static function search(string $keywords, int $page)
    {
        $result = [
            'count' => self::countSelect('`title` LIKE "%' . $keywords . '%"'),
            'data'  => self::pageSelect('*', '`title` LIKE "%' . $keywords . '%"', $page)
        ];
        if (!count($result['data']['tag_list'])) {
            $result['tag_list'] = DB::table('tags')->orderByRaw('rand()')->limit(30)->pluck('name', 'id');
        }
        return $result;
    }
}
